// 递归实现
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
 var preorderTraversal = function(root) {
    // 用于存储遍历结果
    const res = []
    // 设置函数进行递归遍历
    const preorder = (root) => {
       // 当前节点为空时，无需实行递归操作 
       if(!root) {
           return
       }
       // 记录根节点值
       res.push(root.val)
       // 前序遍历左子树
       preorder(root.left)
       // 前段遍历右子树
       preorder(root.right)
    }
    preorder(root)
    return res
};

// 采用栈实现
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
 const preorderTraversal = function(root) {
    const res = []
    const stk = []
    while (root || stk.length) {
      while (root) {
        // 右子结点入栈
        stk.push(root.right)
        // 记录根节点
        res.push(root.val)
        // 下一步处理左子节点
        root = root.left
      }
      // 左子树处理完毕，将 stk 出栈，处理右子树
      root = stk.pop()
    }
    return res
  }

// 采用栈实现
  /**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var preorderTraversal = function(root) {
    if (!root) return [];
    var result = [],
        stack = [root];
    while (stack.length !== 0) {
      var curr = stack.pop();
      if (curr.right) stack.push(curr.right);
      if (curr.left) stack.push(curr.left);
      result.push(curr.val);
    }
    return result;
  };